package com.elong.android.specialhouse.activity;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Intent;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.common.BaseViewHolder;
import com.elong.android.specialhouse.adapter.common.MultiItemType;
import com.elong.android.specialhouse.adapter.common.PowerAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.base.DialogUtils;
import com.elong.android.specialhouse.entity.ChatMessage;
import com.elong.android.specialhouse.entity.ImPushPayloadContent;
import com.elong.android.specialhouse.entity.response.MessageResult;
import com.elong.android.specialhouse.notification.BasicNotificationBuilder;
import com.elong.android.specialhouse.notification.MyNotificationManager;
import com.elong.android.specialhouse.request.AddImReq;
import com.elong.android.specialhouse.request.GetOneUserMessageReq;
import com.elong.android.specialhouse.request.GetUnReadMessageListReq;
import com.elong.android.specialhouse.ui.SuperListView;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.InputFilterUtils;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.android.specialhouse.utils.ToastUtils;
import com.elong.android.specialhouse.utils.filter.BaseFilter;
import com.elong.framework.net.error.NetFrameworkError;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.elong.android.specialhouse.AppConstants.KEY_PAYLOAD;

/**
 * @author lin.chai
 * @Description 聊天详情页
 * @date 2015/9/23 10:17
 * 
 */
@SuppressLint("SimpleDateFormat")
public class ChatActivity extends BaseVolleyActivity<IResponse<?>>
      implements OnClickListener {
	public static final String TAG = ChatActivity.class.getSimpleName() ;
    public static boolean isForground = false ;
	private final static String DATE_FORMAT= "yyyy-MM-dd HH:mm";
	private final static int DATE_INTERVAL= 1000*60*5;
	private final static int PAGE_SIZE= 15;
	private final static int MESSAGE_LENGTH= 200;

	private List<ChatMessage> mDatas = new ArrayList<ChatMessage>();
    private SuperListView lvChat;
    private PowerAdapter<ChatMessage> mAdapter;
    private EditText etInput;
    private Button btnSend;
    private String mRecentDate = null;//记录最新一条消息的时间
    private long mUserId;
    private String mUserName;
    private long mFriendId;
    private String mFriendName;
    private int mPageIndex = 1;
    private int mTotalCount = 0;
	private long mLastMessageId;
    private boolean isRefresh = false;
    
    @Override
    protected void initContentView() {
        setContentView(R.layout.act_chat);
        lvChat = (SuperListView) findViewById(R.id.lv_chat);
        etInput = (EditText) findViewById(R.id.et_input_text);
        etInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MESSAGE_LENGTH)});
        btnSend = (Button) findViewById(R.id.btn_send);
        btnSend.setOnClickListener(this);

        initDatas();
        setupList();
        requestMessageList();
    }
    private void initDatas() {
    	mUserId = Long.parseLong(Account.getInstance().getUserId());
    	mUserName = Account.getInstance().getNickName();
    	if(getIntent() != null){
    		mFriendId = getIntent().getLongExtra(AppConstants.ACTIVITY_KEY_FRIEND_ID, 0);
    		mFriendName = getIntent().getStringExtra(AppConstants.ACTIVITY_KEY_FRIEND_NAME);
    		setHeader(mFriendName);
    	}
    }
	private void setupList() {
        MultiItemType<ChatMessage> multiItemTypeSupport = new MultiItemType<ChatMessage>() {
            @Override
            public int getLayoutId(int position, ChatMessage msg) {
                if (msg.isComMeg()) {
                    return R.layout.item_chat_from_msg;
                }
                return R.layout.item_chat_send_msg;
            }

            @Override
            public int getViewTypeCount() {
                return 2;
            }

            @Override
            public int getItemViewType(int postion, ChatMessage msg) {
                if (msg.isComMeg()) {
                    return ChatMessage.RECIEVE_MSG;
                }
                return ChatMessage.SEND_MSG;
            }
        };
        mAdapter = new PowerAdapter<ChatMessage>(ChatActivity.this, mDatas,
                multiItemTypeSupport) {
            @Override
            protected void convert(BaseViewHolder holder, final ChatMessage item) {
                switch (holder.mItemLayoutId) {
                    case R.layout.item_chat_from_msg:
                        holder.setText(R.id.chat_from_content, item.getContent());
                        if(item.isShowDate()){
							holder.setText(R.id.chat_from_date, getFormatTime(item.getCreateDate()));
                        	holder.setVisible(R.id.chat_from_date, true);
                        } else{
                        	holder.setVisible(R.id.chat_from_date, false);
                        }
						//是否显示包含敏感词的提示信息
						holder.setVisible(R.id.tv_filter_tips, InputFilterUtils.containsSensitiveWords(item.getContent(), ChatActivity.this));

//                        holder.setText(R.id.chat_from_name, item.getName());
						holder.setImageUrl(R.id.chat_from_icon, item.getIcon(), R.drawable.default_user_photo);
						holder.setOnClickListener(R.id.chat_from_icon, new OnClickListener() {
							@Override
							public void onClick(View v) {
								goToHomePageOthers(item.getUid(), item.getName());
							}
						});
                        break;
                    case R.layout.item_chat_send_msg:
                        holder.setText(R.id.chat_send_content, item.getContent());
                        if(item.isShowDate()){
							holder.setText(R.id.chat_send_date, getFormatTime(item.getCreateDate()));
                        	holder.setVisible(R.id.chat_send_date, true);
                        } else{
                        	holder.setVisible(R.id.chat_send_date, false);
                        }
//                        holder.setText(R.id.chat_send_name, item.getName());
                        holder.setImageUrl(R.id.chat_send_icon, item.getIcon(), R.drawable.default_user_photo);
                        break;
                }

            }
		};
		lvChat.setAdapter(mAdapter);
        lvChat.setLastPage();//没有上拉加载
        lvChat.setOnRefreshListener(new SuperListView.OnPullDownRefreshListener() {
			@Override
			public void onRefresh() {
				if (hasMoreMessage()) {
					isRefresh = true;
					requestMessageList();
				} else {
					ToastUtils.show(getString(R.string.no_more_message));
					lvChat.onRefreshComplete();
				}

			}
		});
    }

	/**
	 * 查看他人的个人主页
	 */
	private void goToHomePageOthers(String uid,String name) {
		Intent intent = new Intent(this,HomePageOthersActivity.class);
		intent.putExtra(AppConstants.LANDLORD_ID,uid);
		intent.putExtra(AppConstants.LANDLORD_NAME,name);
		startActivity(intent);
	}

	protected boolean hasMoreMessage() {		
		return mDatas.size() < mTotalCount;
	}

	/** 
     * 获取历史消息记录
     */
    private void requestMessageList() {
		GetOneUserMessageReq req =new GetOneUserMessageReq();
		req.SenderId = mFriendId;//SenderId 为对方id
		req.CollectId = mUserId;//CollectId 为当前用户
		req.TagType = 7;
		req.PSize = PAGE_SIZE;
		req.PNumber = mPageIndex;
		req.LastMessageId = mLastMessageId;
		requestHttp(req, ApartmentAPI.getOneUserMessageList, StringResponse.class,true);
    }
    /**
     * 获取未读消息记录
     */
    private void requestUnReadMessageList() {
        GetUnReadMessageListReq req =new GetUnReadMessageListReq();
        req.SenderId = mFriendId;
        req.CollectId = mUserId;//CollectId 为当前用户
        req.TagType = 7;
        requestHttp(req, ApartmentAPI.getUnReadMessageList, StringResponse.class,false);
    }

    /** 
     * 判断时间间隔，超过5分钟显示时间
     * @param recentDate 最近一条显示消息的时间
     * @param messageDate 当前消息的时间
     * @return boolean
     */
	private boolean checkDateInterval(String recentDate,String messageDate) {
		if(recentDate == null){
			return true;
		}
		SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
		long diff = 0;
		try {
			Date d1 = df.parse(messageDate);
			Date d2 = df.parse(recentDate);
			diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
			if(diff < 0){
				diff = -diff;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return diff > DATE_INTERVAL;
	}
	/**
	 * 显示消息时间的格式
	 * @param messageTime 消息的时间
	 * @return String
	 */
	private  String getFormatTime(String messageTime){
		if(StringUtils.isEmpty(messageTime)){
			return "";
		}
		Calendar c = Calendar.getInstance();
		c.set( Calendar.HOUR_OF_DAY, 0);
		c.set( Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);//今天0点0时0分
		Date today = c.getTime();
		c.add(Calendar.DAY_OF_MONTH, -1);//昨天的日期
		Date yesterday = c.getTime();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date time = null;
		try {
			time = df.parse(messageTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if(time.after(today)){
			return new SimpleDateFormat("HH:mm").format(time);
		}else if(time.after(yesterday) && time.before(today)){
			return getString(R.string.yesterday) + " "
					+ new SimpleDateFormat("HH:mm").format(time);
		}else if(DateTimeUtils.isDateInOneYear(time, today)){//是不是今年的日期
			return new SimpleDateFormat("MM-dd HH:mm").format(time);
		}
		return df.format(time);
	}

	@Override
    public void onClick(View v) {
    	super.onClick(v);
    	if(v.getId() == R.id.btn_send){
    		String input = etInput.getText().toString();
    		if(StringUtils.isEmpty(input)){
    			ToastUtils.show(getString(R.string.no_null_message));
    		}else{
				if (InputFilterUtils.containsSensitiveWords(input, this)) {
					DialogUtils.showInfo(this, R.string.warning, R.string.malicious_tips);
				}
				input = new BaseFilter(input).execute();
				Log.d("filter-->", "after convert" + input);
				sendNewMessage(input);
    		}
    	}
    }
	/** 
	 * 发送新消息
	 * @param inputMessage 输入的消息
	 */
	private void sendNewMessage(String inputMessage) {
	    //向服务器发送新消息
		AddImReq req = new AddImReq();
		req.Content = inputMessage;
        req.SenderId = mUserId;
        req.CollectId = mFriendId;
        req.SenderName = mUserName;
        req.CollectName = mFriendName;
        requestHttp(req, ApartmentAPI.insertMessage, StringResponse.class);
		btnSend.setEnabled(false);//发送消息时禁用发送按钮
		btnSend.setSelected(true);
	}
	/** 
	 * 发送成功后显示新消息
	 * @param inputMessage 输入的消息
	 */
	private void showNewMessage(String inputMessage) {
		String date = DateTimeUtils.formatDateByPattern(Calendar.getInstance(), DATE_FORMAT);
		String icon = Account.getInstance().getAvatar();
		if(StringUtils.isEmpty(icon)){
			icon = "drawable://"+ R.drawable.default_user_photo;
		}
		ChatMessage message = new ChatMessage(icon,mUserName, inputMessage, date, false);
		message.setShowDate(checkDateInterval(mRecentDate,message.getCreateDate()));
		mDatas.add(message);
	    mAdapter.add(message);	 
	    lvChat.setSelection(mDatas.size() - 1);

	    mRecentDate = message.getCreateDate();//更新最新消息时间		
	    mTotalCount++;//消息总数加一
	    etInput.setText("");//清空输入框
	}

	@Override
	public void onTaskCancel(ElongRequest request) {
		super.onTaskCancel(request);
		btnSend.setEnabled(true);
		btnSend.setSelected(false);
	}

	@Override
	public void onTaskTimeoutMessage(ElongRequest request) {
		super.onTaskTimeoutMessage(request);
		btnSend.setEnabled(true);
		btnSend.setSelected(false);
	}

	@Override
	public void onTaskError(ElongRequest request, NetFrameworkError ex) {
		request.setShowDialog(true);
		super.onTaskError(request, ex);
		btnSend.setEnabled(true);
		btnSend.setSelected(false);
	}

	@Override
	public void onTaskPost(ElongRequest request, IResponse<?> t) {
		super.onTaskPost(request, t);
		btnSend.setEnabled(true);//发送完成后启用按钮
		btnSend.setSelected(false);
		JSONObject result = (JSONObject) JSONObject.parse(((StringResponse) t).getContent());
		String errorCode = result.containsKey(JSONConstants.ATTR_ERRORCODE) ? result.getString(JSONConstants.ATTR_ERRORCODE) : "";
		//ErrorCode为104时表示没有消息，不弹框显示错误
		if(errorCode.equals("104") || handleIsError(request, result)){
			return;
		}
    	switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
    		case getOneUserMessageList:
				mPageIndex++;
    			mTotalCount = result.containsKey(JSONConstants.ATTR_MESSAGE_NUM) ? result.getIntValue(JSONConstants.ATTR_MESSAGE_NUM) : 0;
    			List<MessageResult> list = JSON.parseArray(result.getString(JSONConstants.ATTR_MESSAGE_LIST), MessageResult.class);
    			if(list != null && !list.isEmpty()){
    				List<ChatMessage> tempData = convertData(list);
    				if(isRefresh){
    					mDatas.addAll(0, tempData);
    		            mAdapter.addAll(0,tempData);
    		            lvChat.onRefreshComplete();
    				}else{
    				    mDatas.addAll(tempData);
        				mAdapter.addAll(tempData);
        				lvChat.setSelection(tempData.size() - 1);
        				mRecentDate = tempData.get(tempData.size() - 1).getCreateDate();
    				}	
    			}  				
    			break;
            case getUnReadMessageList:
                List<MessageResult> unReadList = JSON.parseArray(result.getString(JSONConstants.ATTR_MESSAGE_LIST), MessageResult.class);
                if(unReadList != null && !unReadList.isEmpty()) {
                    List<ChatMessage> tempData = convertData(unReadList);
					mTotalCount = mTotalCount+tempData.size();
                    mDatas.addAll(tempData);
                    mAdapter.addAll(tempData);
                    lvChat.setSelection(mDatas.size() - 1);
                    mRecentDate = mDatas.get(mDatas.size() - 1).getCreateDate();
                }
                break;
    		case insertMessage:
    			AddImReq req = (AddImReq)request.getRequestOption();
    			showNewMessage(req.Content);
    			break;
		    default:
			    break;
    	}
	}


	/**
	 * 转换服务器返回数据类型
	 * @param list 服务器返回数据
	 * @return List<ChatMessage>
	 */
	private List<ChatMessage> convertData(List<MessageResult> list) {
		List<ChatMessage> datas = new ArrayList<ChatMessage>();
		String recentDate = null;
		//更新每页最后一条消息Id（分页使用）
		mLastMessageId = list.get(list.size()-1).Id;
		//服务器返回的list是时间倒序的，最近的消息在前面
		for(int i=list.size()-1; i>=0 ;i--){
			MessageResult result = list.get(i);
			ChatMessage message = new ChatMessage();			
			message.setContent(result.Content);
			message.setCreateDate(result.SendTime);
			message.setShowDate(checkDateInterval(recentDate,message.getCreateDate()));
			recentDate = message.getCreateDate();
			message.setName(result.SenterName);
            message.setIcon(result.SenterUrl);
			if(result.SenterId == mUserId){
				//发出的消息
				message.setComMeg(false);				
			}else{
				//发来的消息
				message.setComMeg(true);
			}
			datas.add(message);
		}		
		return datas;
	}

    @Override
    protected int getReceiverPriority() {
        return AppConstants.RECEIVER_PRIORITY_CHAT ;
    }

	@Override
	protected void onReceive(Intent intent) {
		ImPushPayloadContent content = (ImPushPayloadContent) intent.getSerializableExtra(KEY_PAYLOAD);
		if(content == null){
			return;
		}
		if (content.recieverId.equals(mUserId+"") && content.senderId.equals(mFriendId +"")) {
			//消息id是当前id则拉取未读消息列表显示
			requestUnReadMessageList();
		} else {
			//通知栏显示
			BasicNotificationBuilder builder = new BasicNotificationBuilder(ChatActivity.this, new BasicNotificationBuilder.GetPendingIntent() {
				@Override
				public PendingIntent getPendingIntent() {
//				Intent toMessageList = new Intent(ChatActivity.this, MessageListActivity.class);
//				PendingIntent contentIntent = PendingIntent.getActivity(ChatActivity.this,0,toMessageList,PendingIntent.FLAG_CANCEL_CURRENT);
					return null;
				}
			});
			MyNotificationManager.getInstanse().setNotificationInterface(builder);
			MyNotificationManager.getInstanse().sendNotification(this, content.senderName, getString(R.string.send_new_message), R.drawable.ic_launcher);
		}
	}

	@Override
    protected void onPause() {
        super.onPause();
        isForground = false ;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isForground = true ;
    }

}
